<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" size="small" label-width="100">
      <el-form-item label="输入搜索：">
        <el-input style="width: 203px" v-model="listQuery.keyword" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品货号：">
        <el-input style="width: 203px" v-model="listQuery.productSn" placeholder="商品货号"></el-input>
      </el-form-item>
      <el-form-item label="商品分类：">
        <el-cascader
          style="width: 203px"
          clearable
          v-model="selectProductCateValue"
          :options="productCateOptions"
          :props="{ label: 'name', value: 'id' }"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="商品品牌：">
        <el-select style="width: 203px" v-model="listQuery.brandId" placeholder="请选择品牌" clearable>
          <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态：">
        <el-select style="width: 203px" v-model="listQuery.publishStatus" placeholder="全部" clearable>
          <el-option v-for="item in PUTAWAY_PRODUCT_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态：">
        <el-select style="width: 203px" v-model="listQuery.verifyStatus" placeholder="全部" clearable>
          <el-option v-for="item in VERIFY_PRODUCT_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearchList()" type="primary" size="small"> 搜索 </el-button>
        <el-button @click="handleResetSearch" size="small"> 重置 </el-button>
        <el-button class="btn-add" @click="handleAddProduct()" size="small"> 添加 </el-button>
      </el-form-item>
    </el-form>
    <div class="table-container">
      <el-table
        ref="productTable"
        :data="list"
        height="100%"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        border
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="编号" width="80" align="center">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="scope"><img style="height: 40px" :src="scope.row.pic" /></template>
        </el-table-column>
        <el-table-column label="商品名称" min-width="250" show-overflow-tooltip align="center">
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" min-width="120" align="center">
          <template #default="scope">
            {{ scope.row.brandName }}
          </template>
        </el-table-column>
        <el-table-column label="价格(元)" width="120" prop="price" align="center"> </el-table-column>
        <el-table-column label="货号" width="120" prop="productSn" align="center"> </el-table-column>
        <el-table-column label="上架" width="80" align="center">
          <template #default="scope">
            <el-switch
              @change="handlePublishStatusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.publishStatus"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="新品" width="80" align="center">
          <template #default="scope">
            <el-switch @change="handleNewStatusChange(scope.row)" :active-value="1" :inactive-value="0" v-model="scope.row.newStatus">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="推荐" width="80" align="center">
          <template #default="scope">
            <el-switch
              @change="handleRecommendStatusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.recommandStatus"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="100" align="center">
          <template #default="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="销量" width="100" align="center">
          <template #default="scope">{{ scope.row.sale }}</template>
        </el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleShowVerifyDetail(scope.row)">
              {{ VERIFY_PRODUCT_STATUS_DICT[scope.row.verifyStatus] }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button size="small" link type="primary" @click="handleShowProduct(scope.row)">查看 </el-button>
            <el-button size="small" link type="primary" @click="handleUpdateProduct(scope.row)">编辑 </el-button>
            <el-button size="small" link type="primary" @click="handleShowLog(scope.row)">日志 </el-button>
            <el-button size="small" link type="primary" @click="handleShowSkuEditDialog(scope.row)"> SKU </el-button>
            <el-button size="small" link type="danger" @click="handleDelete(scope.row)">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option v-for="item in PRODUCT_STATUS_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
      </el-select>
      <el-button class="search-button" @click="handleBatchOperate()" type="primary" size="small"> 确定 </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5, 10, 15]"
        v-model:current-page="listQuery.pageNum"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="编辑货品信息" v-model="editSkuInfo.dialogVisible" width="40%">
      <span>商品货号：</span>
      <span>{{ editSkuInfo.productSn }}</span>
      <el-input placeholder="按sku编号搜索" v-model="editSkuInfo.keyword" size="small" style="width: 50%; margin-left: 20px">
        <template #append>
          <el-button :icon="Search" @click="handleSearchEditSku"></el-button>
        </template>
      </el-input>
      <el-table style="width: 100%; margin-top: 20px" height="100%" :data="skuStockList" border>
        <el-table-column label="SKU编号" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.skuCode"></el-input>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in productAttr" :label="item.name" :key="item.name" align="center">
          <template #default="scope">
            {{ getProductSkuSp(scope.row, index) }}
          </template>
        </el-table-column>
        <el-table-column label="销售价格" width="80" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.price"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品库存" width="80" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.stock"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存预警值" width="100" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.lowStock"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="editSkuInfo.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSkuConfirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {
  fetchList,
  updateDeleteStatus as updateDeleteStatusApi,
  updateNewStatus as updateNewStatusApi,
  updateRecommendStatus as updateRecommendStatusApi,
  updatePublishStatus as updatePublishStatusApi,
} from '@/api/product'
import { fetchList as fetchSkuStockList, update as updateSkuStockList } from '@/api/skuStock'
import { fetchList as fetchProductAttrList } from '@/api/productAttr'
import { fetchList as fetchBrandList } from '@/api/brand'
import { fetchListWithChildren } from '@/api/productCate'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { PRODUCT_STATUS_MAP, PUTAWAY_PRODUCT_STATUS_MAP, VERIFY_PRODUCT_STATUS_MAP, VERIFY_PRODUCT_STATUS_DICT } from '@/constant'
import type { Product, ProductPageParams } from '@/models/product'
import { Search } from '@element-plus/icons-vue'
import type { SkuStock } from '@/models/SkuStock'
import type { ProductCateTree } from '@/models/productCate'
import type { ProductAttr } from '@/models/productAttr'
import type { Brand } from '@/models/brand'

const router = useRouter()

defineOptions({ name: 'ProductList' })
const editSkuInfo = ref({
  dialogVisible: false,
  productId: 0,
  productSn: '',
  productAttributeCategoryId: 0,
  productAttr: [],
  keyword: '',
})
const productAttr = ref<ProductAttr[]>()
const skuStockList = ref<SkuStock[]>([])
const operateType = ref(null)
const listQuery = ref<ProductPageParams>({ pageNum: 1, pageSize: 10 })
const list = ref<Product[]>([])
const total = ref(0)
const listLoading = ref(true)
const selectProductCateValue = ref<number[]>([])
const multipleSelection = ref<Product[]>([])
const productCateOptions = ref<ProductCateTree[]>([])
const brandOptions = ref<Brand[]>([])

getList()
getBrandList()
getProductCateList()
watch(selectProductCateValue, (newValue) => {
  if (newValue != null && newValue.length == 2) {
    listQuery.value.productCategoryId = newValue[1]
  } else {
    listQuery.value.productCategoryId = 0
  }
})

function getProductSkuSp(row: SkuStock, index: number) {
  let spData = JSON.parse(row.spData || '[]')
  if (spData != null && index < spData.length) {
    return spData[index].value
  } else {
    return null
  }
}

async function getList() {
  listLoading.value = true
  const response = await fetchList(listQuery.value)
  listLoading.value = false
  list.value = response.data.data.list
  total.value = response.data.data.total
}

async function getBrandList() {
  const response = await fetchBrandList({ pageNum: 1, pageSize: 100 })
  brandOptions.value = response.data.data.list
}

async function getProductCateList() {
  const response = await fetchListWithChildren()
  productCateOptions.value = response.data.data
}

async function handleShowSkuEditDialog(row: Product) {
  console.log(row)
  editSkuInfo.value.dialogVisible = true
  editSkuInfo.value.productId = row.id as number
  editSkuInfo.value.productSn = row.productSn as string
  editSkuInfo.value.productAttributeCategoryId = row.productAttributeCategoryId as number
  editSkuInfo.value.keyword = ''
  const response = await fetchSkuStockList(row.id as number, { keyword: editSkuInfo.value.keyword })
  skuStockList.value = response.data.data
  if (row.productAttributeCategoryId) {
    const response = await fetchProductAttrList(row.productAttributeCategoryId, { type: 0 })
    productAttr.value = response.data.data.list
  }
}

async function handleSearchEditSku() {
  const response = await fetchSkuStockList(editSkuInfo.value.productId, {
    keyword: editSkuInfo.value.keyword,
  })
  skuStockList.value = response.data.data
}

async function handleEditSkuConfirm() {
  if (!skuStockList.value?.length) {
    ElMessage.warning('暂无sku信息')
    return
  }
  await ElMessageBox.confirm('是否要进行修改', '提示', { type: 'warning' })
  await updateSkuStockList(editSkuInfo.value.productId, skuStockList.value)
  ElMessage.success('修改成功')
  editSkuInfo.value.dialogVisible = false
}

function handleSearchList() {
  listQuery.value.pageNum = 1
  getList()
}

function handleAddProduct() {
  router.push({ path: '/pms/productUpsert' })
}

async function handleBatchOperate() {
  if (operateType.value == null) {
    ElMessage.warning('请选择操作类型')
    return
  }
  if (multipleSelection.value == null || multipleSelection.value.length < 1) {
    ElMessage.warning('请选择要操作的商品')
    return
  }
  await ElMessageBox.confirm('是否要进行该批量操作?', '提示', { type: 'warning' })
  const ids = multipleSelection.value.map((item) => item.id).join(',')
  switch (operateType.value) {
    case PRODUCT_STATUS_MAP[0].value:
      updatePublishStatus(1, ids)
      break
    case PRODUCT_STATUS_MAP[1].value:
      updatePublishStatus(0, ids)
      break
    case PRODUCT_STATUS_MAP[2].value:
      updateRecommendStatus(1, ids)
      break
    case PRODUCT_STATUS_MAP[3].value:
      updateRecommendStatus(0, ids)
      break
    case PRODUCT_STATUS_MAP[4].value:
      updateNewStatus(1, ids)
      break
    case PRODUCT_STATUS_MAP[5].value:
      updateNewStatus(0, ids)
      break
    case PRODUCT_STATUS_MAP[6].value:
      break
    case PRODUCT_STATUS_MAP[7].value:
      updateDeleteStatus(1, ids)
      break
    default:
      break
  }
  getList()
}

function handleSizeChange(val: number) {
  listQuery.value.pageNum = 1
  listQuery.value.pageSize = val
  getList()
}

function handleCurrentChange(val: number) {
  listQuery.value.pageNum = val
  getList()
}

function handleSelectionChange(val: Product[]) {
  multipleSelection.value = val
}

function handlePublishStatusChange(row: Product) {
  updatePublishStatus(row.publishStatus as number, row.id + '')
}

function handleNewStatusChange(row: Product) {
  updateNewStatus(row.newStatus as number, row.id + '')
}

function handleRecommendStatusChange(row: Product) {
  updateRecommendStatus(row.recommandStatus as number, row.id + '')
}

function handleResetSearch() {
  selectProductCateValue.value = []
  listQuery.value = { pageNum: 1, pageSize: 10 }
}

async function handleDelete(row: Product) {
  await ElMessageBox.confirm('是否要进行删除操作?', '提示', { type: 'warning' })
  updateDeleteStatus(1, row.id + '')
}

function handleUpdateProduct(row: Product) {
  router.push({ path: '/pms/productUpsert', query: { id: row.id } })
}

function handleShowProduct(row: Product) {
  console.log('handleShowProduct', row)
}

function handleShowVerifyDetail(row: Product) {
  console.log('handleShowVerifyDetail', row)
}

function handleShowLog(row: Product) {
  console.log('handleShowLog', row)
}

async function updatePublishStatus(publishStatus: number, ids: string) {
  let params = { ids, publishStatus }
  await updatePublishStatusApi(params)
  ElMessage.success('修改成功')
}

async function updateNewStatus(newStatus: number, ids: string) {
  let params = { ids, newStatus }
  await updateNewStatusApi(params)
  ElMessage.success('修改成功')
}

async function updateRecommendStatus(recommendStatus: number, ids: string) {
  let params = { ids, recommendStatus }
  await updateRecommendStatusApi(params)
  ElMessage.success('修改成功')
}

async function updateDeleteStatus(deleteStatus: number, ids: string) {
  let params = { ids, deleteStatus }
  await updateDeleteStatusApi(params)
  ElMessage.success('删除成功')
  getList()
}
</script>
<style></style>
